package indigo.captcha.image;

import java.awt.image.BufferedImage;
import java.awt.image.BufferedImageOp;

import com.octo.captcha.component.image.deformation.ImageDeformation;

public abstract class ThreadLocalFilterDeformer<T extends BufferedImageOp> implements ImageDeformation {
	private final ThreadLocal<T> filterHolder = new ThreadLocal<>();

	protected abstract T createFilter();

	protected abstract void prepareFilter(T filter);

	@Override
	public BufferedImage deformImage(BufferedImage image) {
		T filter = filterHolder.get();
		if (filter == null) {
			filter = createFilter();
			filterHolder.set(filter);
		}
		prepareFilter(filter);
		return filter.filter(image, filter.createCompatibleDestImage(image, image.getColorModel()));
	}
}
